package servlet.client;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import dao.domain.Client;
import service.ClientService;
import service.UserService;
import util.ServletUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.Map;

/**
 * @author gzb
 */
@WebServlet(name = "ClientMainServlet", value = "/ClientMainServlet")
public class ClientMainServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String account = UserService.getAccountFromCookie(request);
        Client client;
        try {
            client = (Client) UserService.selectByAccount("client", account);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        Gson gson = new Gson();
        Map<String, Object> clientMap = gson.fromJson(gson.toJson(client), new TypeToken<Map<String, Object>>() {
        }.getType());
        Date registrationTime = client.getRegistrationTime();
        String registrationTimeStr = ServletUtil.getRegistrationTimeStr(registrationTime);
        clientMap.put("member", ClientService.getMember(client));
        clientMap.put("registrationTime", registrationTimeStr);
        String json = gson.toJson(clientMap);
        response.setContentType("application/json");
        response.getWriter().write(json);
        System.out.println("finish");
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        doGet(request, response);
    }
}
